import os
import sys
import pandas as pd
from datetime import datetime
from calculations import Calculation
import numpy as np

calculate = Calculation()

class DataSolve:
    def __init__(self):
        self.species_counts = []
        self.temperature = 0
        self.actual_do = 0  # 实际溶解氧浓度，单位：mg/L
        self.tp = 0  # 磷含量

    def save_to_xlsx(self, file_path, data):
        current_date = datetime.now().strftime("%Y年%m月%d日")

        try:
            df = pd.read_excel(file_path, engine='openpyxl', index_col=0)
        except FileNotFoundError:
            # 如果文件不存在，创建一个新的DataFrame
            df = pd.DataFrame()

        # 将新数据添加为新的一列
        new_data_df = pd.DataFrame(data, index=[current_date]).T

        # 合并新数据到现有的DataFrame中
        df = pd.concat([df, new_data_df], axis=1)

        df.to_excel(file_path, engine='openpyxl')

    def total_count(self):
        # CSV文件路径
        file_path = '../data/data_example.csv'

        # 使用pandas读取CSV文件
        df = pd.read_csv(file_path)
        columns = 'sum'
        data_matrix = df.loc[0:3, columns]  # pandas的索引是包含起始索引，不包含结束索引的
        data_ = df.loc[7:12, columns]
        self.species_counts = data_matrix.to_numpy()
        self.index_data = data_.to_numpy()

        self.temperature = self.index_data[2]
        self.actual_do = self.index_data[0]
        self.tp = self.index_data[4]


    def analyze(self):
        self.total_count()
        simpson_index = calculate.calculate_simpson_index(self.species_counts)
        pielou_index = calculate.calculate_pielou_index(self.species_counts)
        sdo = calculate.calculate_sdo(self.temperature)
        dosp = calculate.calculate_dosp(self.actual_do, sdo)
        tsi = calculate.calculate_tsi_tp(self.tp)
        data = {
            "SI": simpson_index,
            "PI": pielou_index,
            "SDO": sdo,
            "DOSP": dosp,
            "TSI": tsi
        }
        self.save_to_xlsx('result.xlsx', data)
        print("数据已保存到 result.xlsx")

data_solve = DataSolve()

if __name__ == "__main__":
    data_solve.analyze()
